import configparser

class ConfigReader:
    def __init__(self, file_path, read_string=False):
        self.configPath = file_path
        self.config = configparser.RawConfigParser(comment_prefixes='/', allow_no_value=True)
        self.config.optionxform = str
        self.restore = 0
        if read_string:
            self.config.read_string(file_path)
        else:
            try:
                with open(file_path) as file:
                    self.config.read_file(file)
            except UnicodeDecodeError:
                with open(file_path, encoding="utf-8") as file:
                    self.config.read_file(file)


    def update_recentFile(self, recentList: list):
        self.config._sections["files"]["RecentFile"] = recentList

    def save_Config(self, confDict=None):
        if self.restore:
            recentList = self.config._sections["files"]["RecentFile"]
            self.config.clear()
            self._load_dict_to_dict(confDict)
            self.config._sections["files"]["RecentFile"] = recentList
        elif confDict != None:
            self.config.clear()
            self._load_dict_to_dict(confDict)
        try:
            with open(self.configPath, "w") as file:
                self.config.write(file)
        except:
            with open(self.configPath, "w", encoding="utf-8") as file:
                self.config.write(file)

    def _load_dict_to_dict(self, conf_dict):
        for section_name, section in conf_dict.items():
            self.config.add_section(section_name)
            for key, value in section.items():
                self.config.set(section_name, key, value)

    def get_img(self, img_name):
        """
        获取 [icons] 节中图片路径
        :param img_name: 配置文件中的属性名
        :return: 返回图片相对路径
        """
        return self.config.get("icons", img_name)


    def get_style(self, style_name):
        """
        获取 [styles] 节中的对应属性
        :param style_name: 配置文件中的属性名
        :return: 返回属性值
        """
        return self.config.get("styles", style_name)


    def get_fonts(self, font_name):
        """
        获取 [fonts] 节中的属性
        :param font_name: 配置文件中的属性名
        :return: 返回属性值
        """
        return self.config.get("fonts", font_name)


    def get_settings(self, set_name):
        """
        获取 [settings] 节中的属性
        :param set_name: 配置文件中的属性名
        :return: 返回属性值
        """
        return self.config.get("settings", set_name)

    def get_files(self, file_name):
        """
        获取 [files] 节中的属性
        :param file_name: 配置文件中的属性名
        :return: 返回属性值
        """
        return self.config.get("files", file_name)


